package com.momoauth.common.security.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.momoauth.common.security.config.SecurityConfig;

import java.util.Date;

/**
 * JWT工具类
 */
public class JwtUtil {

    /**
     * 创建令牌
     * @param username
     * @param userId
     * @return
     */
    public static String createToken(String username, Long userId) {
        Date date = new Date(System.currentTimeMillis() + SecurityConfig.expire_time);
        Algorithm algorithm = Algorithm.HMAC256(SecurityConfig.secret);
        return JWT.create()
                .withClaim("username", username)
                .withClaim("userId", String.valueOf(userId))
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 校验token
     * @param token 密钥
     * @return
     */
    public static DecodedJWT verify(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SecurityConfig.secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .build();
        DecodedJWT jwt = verifier.verify(token);
        return jwt;
    }

    /**
     * 解析载荷信息
     * @param token
     * @param name
     * @return
     */
    public static String getClaimName(String token, String name) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim(name).asString();
    }
}
